package leetcode.list;

/**
 * @author mazouri
 * @create 2021-08-18 22:56
 */
public class _160_getIntersectionNode {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null) return null;

        ListNode curA = headA;
        ListNode curB = headB;
        //总长度的差值
        int n = 0;

        while (curA.next != null) {
            n++;
            curA = curA.next;
        }

        while (curB.next != null) {
            n--;
            curB = curB.next;
        }

        //如果最后一个结点不一样，肯定不相交
        if (curA != curB) return null;

        curA = n > 0 ? headA : headB;
        curB = curA == headA ? headB : headA;
        n = Math.abs(n);
        while (n != 0) {
            n--;
            curA = curA.next;
        }

        while (curA != curB) {
            curA = curA.next;
            curB = curB.next;
        }

        return curA;
    }
}
